package com.zg.autoform.web;

import com.zg.autoform.service.ExcelService;
import com.zg.autoform.service.ImportDataService;
import com.zg.autoform.web.vo.ImportProgressVo;
import com.zg.autoform.web.vo.ImportResultVo;
import com.zg.common.core.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 数据导入控制器
 * @author zg
 */
@RestController
@RequestMapping("/import/data")
@RequiredArgsConstructor
@Api(tags = {"数据导入管理"})
@Slf4j
public class ImportDataController {

    private final ExcelService excelService;
    private final ImportDataService importDataService;

    @ApiOperation("下载Excel导入模板")
    @GetMapping("/template/download")
    public void downloadTemplate(@RequestParam Long templateId, HttpServletResponse response) {
        excelService.generateTemplate(templateId, response);
    }

    @ApiOperation("上传并导入数据")
    @PostMapping("/upload")
    public R<ImportResultVo> uploadAndImport(@RequestParam("file") MultipartFile file,
                                           @RequestParam("templateId") Long templateId,
                                           @RequestParam(value = "forceAsync", required = false) Boolean forceAsync) {
        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                return R.error("请选择要导入的文件");
            }

            if (!isExcelFile(file)) {
                return R.error("只支持Excel文件格式（.xlsx、.xls）");
            }

            // 判断处理模式
            boolean needAsync = forceAsync != null ? forceAsync : excelService.needAsyncProcess(file);

            ImportResultVo result;
            if (needAsync) {
                // 异步处理
                result = importDataService.importDataAsync(file, templateId);
                log.info("启动异步导入任务，批次号: {}, 文件: {}", result.getBatchNo(), file.getOriginalFilename());
            } else {
                // 同步处理
                result = importDataService.importDataSync(file, templateId);
                log.info("完成同步导入，批次号: {}, 成功: {}, 失败: {}",
                        result.getBatchNo(), result.getSuccessRows(), result.getFailRows());
            }

            return R.success(result);

        } catch (Exception e) {
            log.error("导入数据失败", e);
            return R.error("导入失败: " + e.getMessage());
        }
    }

    @ApiOperation("查询导入进度")
    @PostMapping("/progress")
    public R<ImportProgressVo> getImportProgress(@RequestParam String batchNo) {
        ImportProgressVo progress = importDataService.getImportProgress(batchNo);
        return R.success(progress);
    }

    /**
     * 检查是否为Excel文件
     */
    private boolean isExcelFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            return false;
        }

        String lowerCaseName = fileName.toLowerCase();
        return lowerCaseName.endsWith(".xlsx") || lowerCaseName.endsWith(".xls");
    }
}
